package com.yeziji.security.common;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.StrUtil;
import com.yeziji.constant.SecuritySal;
import com.yeziji.security.utils.JwtUtils;
import com.yeziji.utils.AesUtils;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.SuperBuilder;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 安全用户信息
 *
 * @author hwy
 * @since 2023/12/04 15:11
 **/
@Data
@SuperBuilder
@NoArgsConstructor
@AllArgsConstructor
public class SecurityUserBase {
    /**
     * 账号
     */
    private String username;

    /**
     * 密码
     */
    private String password;

    /**
     * 登录过期时间
     */
    @Builder.Default
    private long expired = JwtUtils.DEFAULT_EXPIRED;

    /**
     * 加密密码（不可逆）
     *
     * @return {@link String} 加密后的结果
     */
    public String getEncoderPassword() {
        if (StrUtil.isBlank(this.getPassword())) {
            throw new IllegalArgumentException("加密密码不能为空");
        }
        MessageDigest sha256Digest;
        try {
            sha256Digest = MessageDigest.getInstance("SHA-256");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
        sha256Digest.update(this.getPassword().getBytes(StandardCharsets.UTF_8));
        return Base64.encode(sha256Digest.digest());
    }

    /**
     * 获取加密账号
     *
     * @return {@link String} 加密账号
     */
    public String getEncodeUsername() {
        if (StrUtil.isBlank(this.getUsername())) {
            throw new IllegalArgumentException("加密账号不能为空");
        }
        return AesUtils.encrypt(this.getUsername(), SecuritySal.UserSalt.USERNAME_SALT);
    }
}
